package com.syg.FileUpload;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 使用commons-fileupload组件上传文件,该组件是Apache的一个开源项目之一
 * 根据廖雪峰老师博客改编而来
 */
@WebServlet("/commonsfileupload1")
public class _01_Commons_fileupload extends HttpServlet{
    private String uploadDir = "D:\\Cache\\DelTrash\\images";//指定上传文件路径

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1,获取文件上传的实例对象
            ServletFileUpload upload = new ServletFileUpload();
            //2,set max file size to 1 MB(设置当个文件允许的最大大小:1M)
            upload.setFileSizeMax(1024*1024);//upload.setSizeMax(80*1024*1024):设置文件上传表单允许的总大小
            //3,在请求当中获取所有表单项
            FileItemIterator it = upload.getItemIterator(request);
            //4,循环遍历
            while (it.hasNext()){
                //5,获取每一个表单项
                FileItemStream item = it.next();
                //6,判断是否是上传的
                if (!item.isFormField()) {
                    //7,是上传的文件
                    handleFileItem(item);
                }else{
                    //普通表单项
                    //String text = request.getParameter("text");//获取表单请求参数(这样是获取不到)
                    //System.out.println(text);
                    String fieldName = item.getFieldName();//获取普通表单元素名称
                    /**
                     * 这里怎么获取普通表单项的值呢？？？？？？？？？？
                     */
                    System.out.println(fieldName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 在handleFileItem()方法中读取上传文件的输入流
     * @param item
     */
    private void handleFileItem(FileItemStream item) throws IOException {
        System.out.println("upload file name is ===>"+item.getName());
        //1,封装文件保存路径
        File file = new File(uploadDir+"/"+item.getName());
        //2,封装缓存区
        byte[] bys = new byte[1024];
        //3,打开缓存区流
        InputStream is = item.openStream();
        //4,把输出流写入到指定的地方(形成一个文件)
        OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
        for (;;){
            int len = is.read(bys);
            if(len==-1){
                break;
            }
            os.write(bys,0,len);
        }
        //5,释放资源
        is.close();
        os.close();
    }
}
